using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using MvcSoft.Models;
using MvcSoft.Requst;
using MvcSoft.Repository;

namespace MvcSoft.Controllers
{
    public class ProductController : Controller
    {

        public IActionResult Index()
        {
            var category = new EfRepository<Category>();
            var table1 = category.Table.FirstOrDefault();
            if (table1 == null)
            {
                category.Insert(new Category
                {
                    CategoryName = "生活类"
                });
            }
            var product = new EfRepository<Product>();
            var table2 = product.Table.Where(x => x.IsDeleted == false).ToList();
            return View(table2);
        }

        public IActionResult CreateOrEdit(int id)
        {
            if (id == 0)
            {

                return View();
            }
            else
            {
                var product = new EfRepository<Product>();
                var table = product.Table.FirstOrDefault(x => x.IsDeleted == false && x.Id == id);
                return View(table);
            }
        }
        public IActionResult Save(ProductRequst res)
        {
            var product = new EfRepository<Product>();
            if (res.Id == 0)
            {
                product.Insert(new Product
                {
                    ProductName = res.ProductName,
                    Price = res.Price,
                    Stock = res.Stock,
                    Supplier = res.Supplier,
                    CategoryId = 1
                });
            }
            else
            {
                var table = product.Table.FirstOrDefault(x => x.IsDeleted == false && x.Id == res.Id);
                table.ProductName = res.ProductName;
                table.Price = res.Price;
                table.Stock = res.Stock;
                table.Supplier = res.Supplier;
                product.Update(table);
            }
            return Ok();
        }
       
    }
}
